package com.roger.topapp;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.test.InstrumentationRegistry;
import android.util.Log;

import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.manager.Package;
import com.roger.uia.helper.util.FileUtils;
import com.roger.uia.helper.util.PicUtils;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.File;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Main extends UiBase {
    private static final String TAG = "TopAppTest";

    @BeforeClass
    public static void beforeClass() throws Throwable{
        if(!mDevice.isScreenOn()) mDevice.wakeUp();
        if(!mDevice.isNaturalOrientation()) mDevice.setOrientationNatural();
        Package.pac().grantAllPerms(InstrumentationRegistry.getTargetContext().getPackageName());
    }

    @Before
    public void setUp() {
        Log.d(TAG, "-- set up --");
        FileUtils.delFolder(new File(filePath+"TopApp/"));
        FileUtils.createFolder(new File(filePath+"TopApp/"));
        mDevice.pressHome();
    }

    @After
    public void tearDown() {
        Log.d(TAG, "-- tear down --");
        mDevice.pressHome();
    }

    @AfterClass
    public static void afterClass() throws Throwable{

    }

    @Test
    public void install() {
        Bundle para= InstrumentationRegistry.getArguments();
        String url = para.getString("url");
        try {
            if(url!=null && url.startsWith("https://play.google.com/store/apps/details?id=")){
                for(int i = 0; i < 3 ; i++){
                    forceStopApp("com.android.vending");
                    clearApp("com.android.vending");
                    Package.pac().getAppPerms("com.android.vending");
                    mDevice.executeShellCommand("am start -a android.intent.action.VIEW -d " + url);
                    waitObj(objSelect[0],"Install",30);
                    if(existObj(objSelect[0],"Install")) break;
                }
                clickObj(objSelect[0],"Install");
                waitObj(objSelect[0],"OK",5);
                if(existObj(objSelect[0],"OK")){
                    clickObj(objSelect[0],"OK");
                    waitClickObj(objSelect[0],"Install",5);
                }
                waitObj(objSelect[0],"Open",10);
                for(int i = 0; i < 600; i++) {
                    if (objEnabled(objSelect[0],"Open")) break;
                    SystemClock.sleep(waitTime * 3);
                }
                if(objEnabled(objSelect[0],"Open")){
                    Log.d(TAG,"install success");
                    FileUtils.writeFile(filePath+"TopApp/result.txt","install success");
                }else{
                    FileUtils.writeFile(filePath+"TopApp/result.txt","install fail,time out 1800s");
                }
            } else {
                Log.d(TAG,"error args");
            }
            mDevice.pressHome();
            forceStopApp("com.android.vending");
            clearApp("com.android.vending");
        } catch (Throwable e){
            FileUtils.writeFile(filePath+"TopApp/result.txt","install fail");
            mDevice.takeScreenshot(new File(filePath+"TopApp/pic.png"));
            e.printStackTrace();
        } finally {
            mDevice.pressHome();
        }
    }

    @Test
    public void open(){
        Bundle para= InstrumentationRegistry.getArguments();
        String pac = para.getString("pac");
        try {
            Package.pac().grantAllPerms(pac);
            mDevice.pressHome();
            SystemClock.sleep(waitTime);

            //openApp(pac);
            startApp2(pac);
            SystemClock.sleep(waitTime * 10);
            //wait for app opened,time out 10s
            String curPac = mDevice.getCurrentPackageName();
            for(int i = 0;i< 10; i++) {
                if(curPac.equals(pac)) break;
                SystemClock.sleep(waitTime);
                curPac = mDevice.getCurrentPackageName();
            }
            //check screen again
            for(int i=0; i<3; i++){
                if(existObj(objSelect[2],"(?i)GOT IT|.*知道了|OK|确定|CANCEL|取消|No Thanks|不，谢谢|accept|同意.*|继续.*|我已阅读")){
                    clickObj(objSelect[2],"(?i)GOT IT|.*知道了|OK|确定|CANCEL|取消|No Thanks|不，谢谢|accept|同意.*|继续.*|我已阅读");
                    SystemClock.sleep(waitTime * 3);
                } else break;
            }
            SystemClock.sleep(waitTime * 20);
            curPac = mDevice.getCurrentPackageName();
            mDevice.takeScreenshot(new File(filePath+"TopApp/pic.png"));
            SystemClock.sleep(waitTime);
            if(PicUtils.pic().isPicBlack(filePath+"TopApp/pic.png") || PicUtils.pic().isPicWhite(filePath+"TopApp/pic.png")){
                FileUtils.writeFile(filePath+"TopApp/result.txt","Black_White Screen");
            } else if (existObj(objSelect[2],"(?i).*not supported by your device.*|.*您的设备不支持.*|" +
                    ".*contact the developer.*|.*与开发者联系.*|.*Download failed.*|.*下载失败.*")) {
                FileUtils.writeFile(filePath+"TopApp/result.txt","Incompatible");
            } else if (existObj(objSelect[2],"(?i).*isn't responding.*|.*没有响应.*|" +
                    ".*keeps stopping.*|.*has stopped.*|.*停止运行.*")){
                FileUtils.writeFile(filePath+"TopApp/result.txt","ANR_Crash");
                clickObj(objSelect[2],"(?i).*close.*|.*关闭.*");
            } else if (curPac.equals(mDevice.getLauncherPackageName())) {
                FileUtils.writeFile(filePath+"TopApp/result.txt","Force Close");
            } else if (curPac.equals(pac)) {
                FileUtils.writeFile(filePath+"TopApp/result.txt","Open Success");
            } else {
                FileUtils.writeFile(filePath+"TopApp/result.txt","Unknown");
            }

        } catch (Throwable e){
            e.printStackTrace();
        }
    }


    @Test
    public void debug(){
        Log.d(TAG,filePath);
        FileUtils.createFolder(new File(filePath+"TopApp/"));
    }

}
